<!--检测方案的详情-->
<template>
  <el-dialog
    :title="'质检方案详情'"
    :visible.sync="dialogVisible"
    width="75%"
    top="5vh"
    :close-on-click-modal="false"
    append-to-body
    @close="handleClose"
    class="qc-detail-dialog"
  >
    <div v-loading="loading" v-if="detail" class="dialog-content">
      <!-- 基本信息区域 -->
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="方案编号" :span="1">{{ detail.template_code || '-' }}</el-descriptions-item>
        <el-descriptions-item label="方案名称" :span="1">{{ detail.template_name || '-' }}</el-descriptions-item>
        <el-descriptions-item label="检测种类" :span="2">
          {{ formatQcTypes(detail.qc_types) }}
        </el-descriptions-item>
        <el-descriptions-item label="启用状态" :span="1">
          <el-tag :type="detail.enable_flag === 'Y' ? 'success' : 'danger'">
            {{ detail.enable_flag === 'Y' ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ detail.remark || '-' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 切换标签页 -->
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="检测项列表" name="inspection">
          <el-table
            :data="inspectionItems"
            border
            style="width: 100%"
            empty-text="暂无检测项"
            size="mini"
            :max-height="tableHeight"
          >
            <el-table-column prop="index_name" label="检测项名称" width="120"></el-table-column>
            <el-table-column prop="index_code" label="检测项编码" width="120"></el-table-column>
            <el-table-column prop="index_type" label="检测项类型" width="100">
              <template slot-scope="scope">
                {{ formatItemType(scope.row.index_type) }}
              </template>
            </el-table-column>
            <el-table-column prop="stander_val" label="标准值" width="90">
              <template slot-scope="scope">
                {{ scope.row.stander_val || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="threshold_max" label="误差上限" width="80">
              <template slot-scope="scope">
                {{ scope.row.threshold_max || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="threshold_min" label="误差下限" width="80">
              <template slot-scope="scope">
                {{ scope.row.threshold_min || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="60">
              <template slot-scope="scope">
                {{ scope.row.unit || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="qc_tool" label="检测工具" width="100">
              <template slot-scope="scope">
                {{ scope.row.qc_tool || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="check_method" label="检测要求" min-width="150">
              <template slot-scope="scope">
                {{ scope.row.check_method || '-' }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="关联物料/产品" name="materials">
          <el-table
            :data="relatedMaterials"
            border
            style="width: 100%"
            empty-text="暂无关联物料/产品"
            size="mini"
            :max-height="tableHeight"
          >
            <el-table-column prop="material_code" label="物料编码" width="120">
              <template slot-scope="scope">
                {{ scope.row.material_code || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="material_name" label="物料名称" width="150">
              <template slot-scope="scope">
                {{ scope.row.material_name || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="material_sfn" label="规格型号" width="120">
              <template slot-scope="scope">
                {{ scope.row.material_sfn || '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="60">
              <template slot-scope="scope">
                {{ scope.row.unit || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="最低检测数" width="90">
              <template slot-scope="scope">
                {{ scope.row.quantity_check_num || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="最大不合格数" width="90">
              <template slot-scope="scope">
                {{ scope.row.quantity_unqualified_num || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="致命缺陷率(%)" width="100">
              <template slot-scope="scope">
                {{ scope.row.cr_rate || '0' }}
              </template>
            </el-table-column>
            <el-table-column label="严重缺陷率(%)" width="100">
              <template slot-scope="scope">
                {{ scope.row.maj_rate || '0' }}
              </template>
            </el-table-column>
            <el-table-column label="轻微缺陷率(%)" width="100">
              <template slot-scope="scope">
                {{ scope.row.min_rate || '100' }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { selectQcTemplateIndexList, selectQcTemplateProductList } from '@/api/qc/QualitySchemeOrder';

// 检测类型映射
const QC_TYPE_MAP = {
  '1': '自制工序检验',
  '2': '首检',
  '3': '巡检',
  '4': '来料检验',
  '5': '成品检验',
  '6': '生产退料检验',
  '7': '销售退货检验',
  '8': '出货检验'
};

// 检测项类型映射
const INDEX_TYPE_MAP = {
  '1': '尺寸检测',
  '2': '外观检测',
  '3': '性能检测',
  '4': '材质检测'
};

export default {
  props: {
    visible: Boolean,
    detail: {
      type: Object,
      default: () => ({
        template_id: null,
        template_code: '',
        template_name: '',
        qc_types: '',
        enable_flag: 'Y',
        remark: ''
      }),
      validator: value => value !== null
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      loading: false,
      inspectionItems: [],
      relatedMaterials: [],
      tableHeight: 250, // 初始表格高度
      activeTab: 'inspection' // 默认激活的标签页
    }
  },
  mounted() {
    this.adjustTableHeight();
    window.addEventListener('resize', this.adjustTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.adjustTableHeight);
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal;
      if (newVal && this.detail && this.detail.template_id) {
        this.fetchData();
        this.$nextTick(this.adjustTableHeight);
      }
    }
  },
  methods: {
    adjustTableHeight() {
      // 根据窗口高度动态调整表格高度
      const windowHeight = window.innerHeight;
      this.tableHeight = Math.max(200, windowHeight * 0.4); // 调整高度比例
    },
    handleClose() {
      this.$emit('update:visible', false);
    },
    handleTabClick(tab) {
      // 切换标签页时调整表格高度
      this.$nextTick(this.adjustTableHeight);
    },
    formatQcTypes(qcTypes) {
      if (!qcTypes) return '-';
      
      // 处理字符串类型（可能是逗号分隔的字符串）
      if (typeof qcTypes === 'string') {
        // 尝试分割字符串（如果是逗号分隔的值）
        if (qcTypes.includes(',')) {
          return qcTypes.split(',')
            .map(type => QC_TYPE_MAP[type.trim()] || type.trim())
            .join(', ');
        }
        return QC_TYPE_MAP[qcTypes] || qcTypes;
      }
      
      // 处理数组类型
      if (Array.isArray(qcTypes)) {
        return qcTypes.map(type => QC_TYPE_MAP[type] || type).join(', ');
      }
      
      // 处理数字类型（如果qcTypes是数字）
      if (typeof qcTypes === 'number') {
        return QC_TYPE_MAP[qcTypes.toString()] || qcTypes;
      }
      
      return '-';
    },
    formatItemType(type) {
      if (!type) return '-';
      return INDEX_TYPE_MAP[type] || type;
    },
    async fetchData() {
      try {
        this.loading = true;
        const templateId = this.detail.template_id;
        
        const [inspectionRes, materialsRes] = await Promise.all([
          selectQcTemplateIndexList(templateId, {}),
          selectQcTemplateProductList(templateId)
        ]);
        
        // 处理检测项数据
        this.inspectionItems = (inspectionRes.rows || []).map(item => ({
          ...item,
          stander_val: item.stander_val != null ? item.stander_val : '-',
          threshold_max: item.threshold_max != null ? item.threshold_max : '-',
          threshold_min: item.threshold_min != null ? item.threshold_min : '-'
        }));
        
        // 处理物料数据
        this.relatedMaterials = (materialsRes.rows || []).map(item => ({
          ...item,
          quantity_check_num: item.quantity_check_num != null ? item.quantity_check_num : '-',
          quantity_unqualified_num: item.quantity_unqualified_num != null ? item.quantity_unqualified_num : '-',
          cr_rate: item.cr_rate != null ? item.cr_rate : '0',
          maj_rate: item.maj_rate != null ? item.maj_rate : '0',
          min_rate: item.min_rate != null ? item.min_rate : '100'
        }));
        
      } catch (error) {
        console.error('获取详情数据失败:', error);
        this.$message.error('获取详情数据失败: ' + error.message);
        this.inspectionItems = [];
        this.relatedMaterials = [];
      } finally {
        this.loading = false;
      }
    }
  }
}
</script>

<style scoped>
.qc-detail-dialog >>> .el-dialog {
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.qc-detail-dialog >>> .el-dialog__body {
  flex: 1;
  overflow: hidden;
  padding: 15px 20px;
  display: flex;
  flex-direction: column;
}

.dialog-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.el-descriptions {
  margin-bottom: 15px;
}

.el-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.el-tabs >>> .el-tabs__content {
  flex: 1;
  overflow: hidden;
}

.el-tabs >>> .el-tab-pane {
  height: 100%;
}

.el-table {
  height: 100%;
}

.dialog-footer {
  text-align: center;
  padding: 10px 0;
}
</style>